package com.sherlocky.document.service;

import com.alibaba.fastjson.JSON;
import com.sherlocky.document.constant.DocumentConstants;
import com.sherlocky.document.entity.Document;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 基于Redis的文档缓存业务实现
 * <p>成功配置了Redis时，注入该Bean</p>
 *
 * TODO 超时时间是否考虑？
 *
 * @author: zhangcx
 * @date: 2019/8/13 15:50
 */
@Slf4j
@Service
@ConditionalOnProperty(prefix = "document.cache.redis", name = "enabled", matchIfMissing = false)
public class RedisDocumentCacheService implements DocumentCacheService {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    /*@Resource(name="redisTemplate")
    private HashOperations<Object, Object, Object> hashOps;*/
    @Resource(name="redisTemplate")
    private ValueOperations<Object, Object> valOps;

    @Override
    public boolean put(String documentKey, Document doc) {
        if (doc == null) {
            return false;
        }
        valOps.setIfAbsent(cacheKey(documentKey), JSON.toJSONString(doc), DocumentConstants.CACHE_DURATION);
        //hashOps.put(DocumentConstants.DOCUMENT_REDIS_KEY_PREFIX_FORMAT, documentKey, JSON.toJSONString(doc));
        return true;
    }

    @Override
    public Document get(String documentKey) {
        /*return JSON.parseObject((String) hashOps.get(DocumentConstants.DOCUMENT_REDIS_KEY_PREFIX_FORMAT, documentKey), Document.class);*/
        return JSON.parseObject((String) valOps.get(cacheKey(documentKey)), Document.class);
    }

    @Override
    public void remove(String documentKey) {
        /*hashOps.delete(DocumentConstants.DOCUMENT_REDIS_KEY_PREFIX_FORMAT, documentKey);*/
        redisTemplate.delete(cacheKey(documentKey));
    }

    private String cacheKey(String documentKey) {
        return String.format(DocumentConstants.DOCUMENT_REDIS_KEY_PREFIX_FORMAT, documentKey);
    }
}
